<?php

/**
 * Author: xx.com
 */
namespace Api\Controller;

use Think\Controller;
use Api\Logic\GoodsLogic;
use Think\Page;

class CartController extends BaseController
{

    public $cartLogic; // 购物车逻辑操作类


    /**
     * 析构流函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->cartLogic = new \Home\Logic\CartLogic();

        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        //$user_id = I("user_id",0); // 用户id                       
        // 给用户计算会员价 登录前后不一样
        if ($this->user_id) {
            $user = M('users')->where("user_id = {$this->user_id}")->find();
            M('Cart')->execute("update `__PREFIX__cart` set member_goods_price = goods_price * {$user[discount]} where (user_id ={$user[user_id]} or session_id = '{$unique_id}') and prom_type = 0");
        }
		
    }
	
    //删除购物车商品。单删或者批删
    public function del_cart()
    {
        $goods_id = I('goods_id', ''); // 有可能是多个, 如果是多个用逗号做为分隔
        if ($goods_id == '') {
            $this->returnInfo(-1, '请选择删除的商品');
        }

        $where['goods_id'] = array('in', $goods_id);
        if ($this->dels($where)) {
            $this->returnInfo('1', '删除成功');
        } else {
            $this->returnInfo('-1', '删除失败, 未知原因');
        }
    }
	
    /**
     * 删除购物车商品
     * @param $where 删除条件
     * @return bool
     */
    public function dels($where)
    {
        $goods = M('cart')->where('user_id=' . $this->user_id)->where($where)->select();
        if (empty($goods)) {
            $this->returnInfo('-1', '购物车中已删除，请勿重复删除');
        }
        if (M('cart')->where('user_id=' . $this->user_id)->where($where)->delete() !== false) {
            return true;
        }
        return false;
    }
	
    /*
     * 请求获取购物车列表
     */
    public function cartList()
    {
        $cart_form_data = $_POST["cart_form_data"]; // goods_num 购物车商品数量
        $cart_form_data = json_decode($cart_form_data, true); //app 端 json 形式传输过来

        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
//        $user_id = I("user_id",0); // 用户id       

        $where = " session_id = '$unique_id' "; // 默认按照 $unique_id 查询
        $this->user_id && $where = " user_id = " . $this->user_id; // 如果这个用户已经等了则按照用户id查询
        $cartList = M('Cart')->where($where)->order(array('add_time' => 'desc'))->getField("id,goods_num,selected,goods_id");

        if ($cart_form_data) {
            // 修改购物车数量 和勾选状态
            foreach ($cart_form_data as $key => $val) {
                $data['goods_num'] = $val['goodsNum'];
                $data['selected'] = $val['selected'];
                $cartID = $val['cartID'];
                if (($cartList[$cartID]['goods_num'] != $data['goods_num']) || ($cartList[$cartID]['selected'] != $data['selected']))
                    M('Cart')->where("id = $cartID")->save($data);
            }
        }
        $result = $this->cartLogic->cartList($this->user, $unique_id, 0, 0); // 选中的商品
        exit(json_encode($result));
    }


    /**
     * 购物车第二步确定页面
     */
    public function cart2()
    {
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        $usersInfo = get_user_info($this->user_id);  // 用户
        if ($this->user_id == 0) exit(json_encode(array('status' => -1, 'msg' => '用户user_id不能为空', 'result' => '')));
        if ($this->cartLogic->cart_count($this->user_id, 1) == 0) exit(json_encode(array('status' => -2, 'msg' => '你的购物车没有选中商品', 'result' => '')));



        $cartModel = M('Cart');
        $shopModel = M('Shop');
        $goodsModel = M('Goods');

        // 购物车商品
        $where['c.status'] = 1;
        $where['c.user_id'] = $this->user_id;
        $where['c.selected'] = 1;

        $cartGoodsList = $cartModel->where($where)->alias('c')
            ->join('ln_goods as g on g.goods_id=c.goods_id')
            ->field('c.id,c.user_id,c.session_id,c.member_goods_price,c.bar_code,c.sku,g.goods_remark,g.goods_id,c.goods_name,c.goods_num,
            c.shop_id,c.market_price,c.goods_price,c.spec_key,c.spec_key_name,c.selected,c.add_time,c.prom_id,c.prom_type,c.prom_price,
            c.status,g.is_free_shipping,g.exchange_integral,original_img')
            ->select();
        $cart_count = count($cartGoodsList);
        $shopGoodsModel = M('shop_goods');
        //$shop_goods_array_goods = array();
        $shop_goods_array_shop = array();
        $goods_list = array();

        $field_goods = array('goods_id', 'goods_name', 'weight', 'market_price', 'integral_price', 'shop_price', 'cost_price',
            'is_on_sale', 'is_free_shipping', 'prom_type', 'prom_id', 'shop_goods_type', 'is_city','original_img','exchange_integral',
            'goods_sn',);
        foreach($cartGoodsList  as $cg_val){
            //商品状态
            $goods = $goodsModel->field($field_goods)->where(array('goods_id'=>$cg_val['goods_id']))->find();
            if(!$goods || $goods['is_on_sale'] == 0){
                $cartModel->where(array('id'=>$cg_val['id']))->delete();
                $this->returnInfo(0, '存在无效商品，请重新操作');
            }
            $goods['goods_num'] = $cg_val['goods_num'];
            $goods_list[$goods['shop_goods_type']][] = $goods;
            //店铺商品信息
            $shop_goods_list = $shopGoodsModel->alias('shop_goods')
                ->field('shop_goods.*')
                ->join('ln_shop as shop on shop_goods.shop_id = shop.id', 'left')
                ->where(array('shop_goods.goods_id'=>$cg_val['goods_id'], 'shop_goods.shop_on_sale'=>1,
                    'shop_goods.store_count'=>array('egt', $cg_val['goods_num']), 'shop.is_open'=>1))
                ->select();

            if($shop_goods_list){
                foreach($shop_goods_list as $sg_val){
                    $sg_val['shop_goods_type'] = $goods['shop_goods_type'];
                    $shop_goods_array_shop[$goods['shop_goods_type']][$sg_val['shop_id']][$sg_val['goods_id']] = $sg_val;
                }
                //$shop_goods_array_goods[$cg_val['goods_id']] = $shop_goods_list;
            }else{
                $this->returnInfo(0, '配送渠道库存不足');
            }
        }

        $real_shop_list = array();
        foreach($goods_list as $key => $val){
            foreach($shop_goods_array_shop[$key] as $key2 => $value2){
                if(count($val) == count($value2)){
                    $real_shop_list[$key][] = $key2;
                }
            }
        }

        $shop_goods_array_full = array();
        $shop_ids = array();
        foreach($shop_goods_array_shop as $key => $sgs_val){
            if(count($sgs_val) == $cart_count){
                $shop_goods_array_full[$key] = $sgs_val;
                $shop_ids[] = $key;
            }
        }

        $addresslist = M('UserAddress')
            ->where(["user_id"=>$this->user_id])
            ->order("is_default desc")
            ->limit(1)
            ->select();
        $latitude = -1;
        $longitude = -1;
        if($addresslist){
            $latitude = $addresslist[0]['latitude'];
            $longitude = $addresslist[0]['longitude'];
        }

        $fields = array('id as shop_id', 'shop_name', 'shop_head_img', 'latitude', 'longitude');
        $order = 'id desc';
        if($latitude != -1 && $longitude != -1 ){
            $fields[] = '(2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*('.$latitude.'-latitude)/360),2)+COS(3.1415926535898*'.$latitude.'/180)* COS(latitude * 3.1415926535898/180)*POW(SIN(3.1415926535898*('.$longitude.'-longitude)/360),2))))*1000 as juli';
            $order .= ' , juli asc';
        }else{
            $fields[] = '0 as juli';
        }
        $shop_where['is_open'] = 1;

        foreach($real_shop_list as $key => $val){

            $shop_where['id'] = array('in', $val);

            $shop_info = $shopModel->field($fields)
                ->where($shop_where)
                ->order($order)
                ->find();
            if($shop_info){
                $shop_list_last[$key] = $shop_info;
            }else{
                $this->returnInfo(0, '暂无配送渠道');
                break;
            }
        }
        //print_r($shop_list_last);
        $shop_goods_list_real = array();
        foreach($shop_list_last as $key => $val){
            $shop_goods_list_real[$key] = $shop_goods_array_shop[$key][$val['shop_id']];
        }

        $dada_distance = tpCache('shopping.dd_distance') ? tpCache('shopping.dd_distance') : 7;
        $dada_distance = bcmul($dada_distance, 1000, 2);
        foreach($goods_list as $key => $t_val){
            foreach($t_val as $g_val){
                $promPrice = calcGoodsPrice($g_val);
                if( $promPrice['is_prom'] )
                {
                    $prom_type = $g_val['prom_type'];    // 0 普通订单, 3 促销优惠
                    $prom_id = $g_val['prom_id'];      // 活动id
                }else{
                    $prom_type = 0;    // 0 普通订单, 3 促销优惠
                    $prom_id = 0;      // 活动id
                }
                $price = $promPrice['price'];

                $goods_info = $shop_goods_list_real[$key][$g_val['goods_id']];
                $goods_info['goods_price'] = $g_val['shop_price'];
                $goods_info['original_img'] = parseMediaUrl($g_val['original_img']);
                $goods_info['exchange_integral'] = $g_val['exchange_integral'];
                $goods_info['member_goods_price'] = $price;
                $goods_info['prom_type'] = $g_val['prom_type'];
                $goods_info['prom_id'] = $g_val['prom_id'];
                $goods_info['prom_price'] = $price;
                $goods_info['goods_sn'] = $g_val['goods_sn'];
                $goods_info['goods_name'] = $g_val['goods_name'];
                $goods_info['market_price'] = $g_val['market_price'];
                $goods_info['is_free_shipping'] = $g_val['is_free_shipping'];
                $goods_info['weight'] = $g_val['weight'];
                $goods_info['goods_num'] = $g_val['goods_num'];
                $goods_info['is_city'] = $g_val['is_city'];
                $goods_info['shop_goods_type'] = $g_val['shop_goods_type'];
                if($goods_info['is_city'] == 1 && $shop_list_last[$key]['juli'] > $dada_distance){
                    $this->returnInfo(0, "商品".$goods_info['goods_name']."超出配送范围",
                        array('shop_dist'=>$dada_distance,
                            'real_dist'=>$shop_list_last[$key]['juli'],
                            'goods_id'=>$goods_info['goods_id']
                        ));
                    break;
                }
                $return_goods_array[$shop_list_last[$key]['shop_id']][] = $goods_info;
            }

        }
//print_r($return_goods_array);
        $shop_list_last_new = array();
        foreach($shop_list_last as $key => $val){
            $val['shop_goods_type'] = $key;
            $shop_list_last_new[$val['shop_id']] = $val;
        }

        $return_data = array();
        $total_price_sum = 0;
        $post_fee_sum = 0;
        $cut_fee_sum = 0;
        $market_cut_fee_sum = 0;
        $all_exchange_integral = 0;
        $num_sum = 0;
        foreach($return_goods_array as $key => $rg_val){

            $return_data_val = array();
            $return_data_val['shop_id'] = $shop_list_last_new[$key]['shop_id'];
            $return_data_val['shop_name'] = $shop_list_last_new[$key]['shop_name'];
            $return_data_val['shop_head_img'] = $shop_list_last_new[$key]['shop_head_img'];
            $return_data_val['shop_goods_type'] = $shop_list_last_new[$key]['shop_goods_type'];
            $return_data_val['shop_info'] = $shop_list_last_new[$key];
            $return_data_val['selected'] = 1;

            $total_price = 0;
            $weight = 0;
            $cut_fee = 0;
            $anum = 0;
            $market_cut_fee = 0;
            foreach($rg_val as &$rgv_val){
                $all_exchange_integral = bcadd($all_exchange_integral, bcmul($rgv_val['exchange_integral'], $rgv_val['goods_num'], 2), 2);
                $rgv_val['goods_fee'] = bcmul($rgv_val['member_goods_price'], $rgv_val['goods_num'], 2);
                $total_price = bcadd($total_price, $rgv_val['goods_fee'], 2);
                $cut_fee = bcadd($cut_fee, bcmul(bcsub($goods['shop_price'], $rgv_val['member_goods_price'],2), $rgv_val['goods_num'], 2), 2);
                if(!$rgv_val['is_free_shipping']){
                    $weight = bcadd($weight , bcmul($rgv_val['weight'], $rgv_val['goods_num']));
                }
                $anum += $rgv_val['goods_num'];
                $market_cut_fee = bcadd($market_cut_fee, bcmul(bcsub($goods['market_price'], $rgv_val['member_goods_price'],2), $rgv_val['goods_num'], 2), 2);
            }

            $return_data_val['cartList'] = $rg_val;
            if($return_data_val['shop_goods_type'] == 1){
                $post_fee = 0;
            }else{
                $post_fee = \Common\Logic\FeeLogic::getPostFeeNew($rgv_val['shop_id'],$weight, $total_price,$shop_info['juli']);
            }


            $return_data_val['total_price']['total_fee'] = $total_price;
            $return_data_val['total_price']['post_fee'] = $post_fee;
            $return_data_val['total_price']['cut_fee'] = $cut_fee;
            $return_data_val['total_price']['num'] = $anum;
            $return_data_val['total_price']['market_cut_fee'] = $market_cut_fee;

            $return_data['cartList'][] = $return_data_val;

            $total_price_sum = bcadd($total_price_sum, $total_price,2);
            $post_fee_sum = bcadd($post_fee_sum, $post_fee, 2);
            $cut_fee_sum = bcadd($cut_fee_sum, $cut_fee, 2);
            $market_cut_fee_sum = bcadd($market_cut_fee_sum, $market_cut_fee, 2);
            $num_sum += $anum;
        }
        //print_r($return_data);

        $totalPriceArray = array(
            "total_fee" => $total_price_sum,
            "post_fee" => $post_fee_sum,
            "cut_fee" => $cut_fee_sum,
            "num" => $num_sum,
            "market_cut_fee" =>  $market_cut_fee_sum
        );

        $point_ex_rate = tpCache('shopping.point_rate');//积分兑换比例
        $order_amount_point = intval($total_price * $point_ex_rate);
        $all_exchange_integral = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分

        $return_data['totalPrice'] = $totalPriceArray;
        $return_data['addressList'] = $this->getAddressInfo($addresslist);
        $return_data['couponList'] = [];
        $return_data['available_points'] = isset($usersInfo['pay_points']) ? $usersInfo['pay_points'] : 0;
        $return_data['all_pay_point'] = $all_exchange_integral;
        $return_data['integral_money'] = bcdiv($all_exchange_integral , $point_ex_rate,2);

        setcookie('cn', $num_sum, null, '/');
        $this->returnInfo(1, '购物车确认', $return_data);
        //exit(json_encode($return_data));
    }


    // 确认订单，创建订单准备支付
    public function cart3()
    {
        try {
            $is_buyNow = I('is_buyNow');
            $goods_id = I('goods_id');
            $goods_num = I('goods_num');
            //$shop_id = I('shop_id', '');
            $remark = I('user_note', '');
            $address_id = I('address_id', 0, 'intval');
            $shop_express = I('shipping_price', '');
            $coupon_id = I("coupon_price", 0); //  优惠券
            $pay_points = I("pay_points"); // 是否使用 积分抵扣支付 true 订单能使用多少积分就用多少，具体的值时，使用具体积分

            $invoice_title = I("invoice_title", 0);

            $usersInfo = M('users')->where([
                "user_id" => $this->user_id
            ])->field("user_id,pay_points,user_money")->find();

            if( $address_id < 1 )
            {
                $this->returnInfo(-1,"请填写收货地址");
            }

            //$goods_spec = I("goods_spec"); // 商品规格
            //$goods_spec = explode(',', $goods_spec);
            //$goods_spec = implode('_', $goods_spec);

            #团购准备支付
            $group_buy_id = I("groupbuy_id", 0);
            if ($group_buy_id) {
                try {
                    $res = \Common\Logic\GroupbuyLogic::createOrder([
                        "user_id" => $this->user_id,
                        "groupbuy_id" => $group_buy_id,
                        //"spec_key" => $goods_spec,
                        "num" => $goods_num,
                        "address_id" => $address_id,
                        "user_note" => $remark,
                    ]);
                } catch (\Exception $e) {
                    $this->returnInfo($e->getCode(), $e->getMessage(), "");
                }

                $this->returnInfo(1, "下单成功", [
                    "postFee" => $res['shipping_price'],
                    "couponFee" => 0,
                    "payables" => $res['order_amount'],
                    "goodsFee" => $res['goods_price'],
                    "pointsFee" => 0,
                    "order_sn" => $res['order_sn'],
                    'pay_points' => 0,// 订单使用积分
                    'available_user_money' => 0,// 可使用余额
                ]);
            }

            // 订单中的能使用的积分是是否全部使用
            $pay_with_all_points = false;

            if ($pay_points == 'true') {
                $pay_points = true;
                $pay_with_all_points = true;

            } else {
                $pay_points = intval($pay_points);
            }

            $remark_array = [];

            if( $remark!='' )
            {
                $remark_array = json_decode($remark,TRUE);
                
                if(  !$remark_array || !is_array($remark) )
                {
                    $remark_array = explode(',', $remark);
                }
            }

            //$shop_id != '' && $shop_id_array = explode(',', $shop_id);
            $shop_express != '' && $shop_express_array = explode(',', $shop_express);

            $coupon_id != '' && $coupon_id_array = explode(',', $coupon_id);


            if ($is_buyNow == '1') 
            {
                #立即购买
                $order_sn = $this->cartLogic->addOrder($this->user_id, $address_id, $invoice_title, $coupon_id, null, $remark, 0, $goods_id, $goods_num,$pay_points); // 添加订单
            }else{
                #购物车下单
                $order_sn = $this->addToOrder($address_id, 0, $shop_express_array, $remark_array, $goods_id, $goods_num, $pay_points);
            }
        } catch (\Exception $e) {
            doLog("[Exception]\r\n[msg]{$e->getMessage()}\r\n[file]{$e->getFile()}\r\n[line]{$e->getLine()}", "error");
            // $this->returnInfo(-1,"系统错误：".$e->getMessage()."--{$e->getLine()}--");
            // if($e->getCode()== 22003)
            // {
            //     $this->returnInfo(-1,"库存不足");
            // }
            $this->returnInfo(-1, $e->getMessage());
        }

        if( $order_sn && is_string( $order_sn ) )
        { 
            #查出订单信息输出
            $order = M('order')->where([
                "order_sn" => $order_sn
            ])->field("order_id,order_sn,user_id,shipping_price,order_amount,goods_price,coupon_price,user_money,integral_money,integral")->find();
            $res = array(
                'postFee' => $order['shipping_price'] , // 物流费
                'couponFee' => $order['coupon_price']?$order['coupon_price']:0, // 优惠券
                'payables' => $order['order_amount'] , // 应付金额
                'goodsFee' => $order['goods_price'],// 商品价格
                'pointsFee' => $order['integral_money'],// 使用积抵消的价格
                'pay_points' => $order['integral']?$order['integral']:0,// 订单使用积分
                'order_sn' => $order['order_sn'],// 订单号
                'available_user_money' => $usersInfo ? $usersInfo['user_money'] : 0,// 可使用余额
            );
            return $this->returnInfo("1", "添加订单成功", $res);
        }
        $this->returnInfo("-1", $order_sn['msg'] ? $order_sn['msg'] : "添加订单失败", ""); 
    }




    /**
     * 定单入库
     * @param int $address_id 收货地址ID
     * @param array $shop_id_array 商店ID数组
     * @param array $shop_express_array 运费到付
     * @param array $remark_array 留言数组, 商店ID作为下标
     * @param array $pay_points 使用多少积分
     * @return array
     */
    public function addToOrder($address_id, $shop_id_array, $shop_express_array, $remark_array, $goods_id, $goods_num, $pay_points = 0)
    {
        //防止灌水
        $order_count = M('Order')->where("user_id= $this->user_id and order_sn like '" . S . date('Ymd') . "%'")->count(); // 查找购物车商品总数量
        if ($order_count >= 100)
            return array('status' => -9, 'msg' => '一天只能下100个订单', 'result' => '');

        $userAddressInfo = $this->getUserAddressInfo($address_id);
        if (empty($userAddressInfo)) {
            $this->returnInfo(-1, '收货地址不存在');
        }

        $result = $this->checkCart(); // 判断购物车是否正常, 商品是否能够购买
        if ($result['status'] == 0) {
            return $result;
        }

        // 获取购物车信息
        $where['selected'] = 1; // 只查询已经选定的
        $where['status'] = 1; // 商品有效
        $where['user_id'] = $this->user_id;
        M()->startTrans(); // 开启事务
        $main_order_sn = 'M' . $this->_createOrderSN();
        // 按店铺进行子订单隔离
        $cartModel = M('cart');
        $cartGoodsList = $cartModel
            ->where($where)
            ->select();

        if (empty($cartGoodsList)) {
            $this->returnInfo(-1, '空的购物车!');
        }
        $cart_count = count($cartGoodsList);

        $latitude = $userAddressInfo['latitude'];
        $longitude = $userAddressInfo['longitude'];

        $goodsModel = M('goods');
        $shopGoodsModel=M('shop_goods');

        foreach($cartGoodsList  as $cg_val){
            //商品状态
            $goods = $goodsModel->where(array('goods_id'=>$cg_val['goods_id']))->find();
            if(!$goods || $goods['is_on_sale'] == 0){
                $cartModel->where(array('id'=>$cg_val['id']))->delete();
                $this->returnInfo(0, '存在无效商品，请重新操作');
            }
            $goods['goods_num'] = $cg_val['goods_num'];
            $goods_list[$goods['shop_goods_type']][] = $goods;
            //店铺商品信息
            $shop_goods_list = $shopGoodsModel->alias('shop_goods')
                ->field('shop_goods.*')
                ->join('ln_shop as shop on shop_goods.shop_id = shop.id', 'left')
                ->where(array('shop_goods.goods_id'=>$cg_val['goods_id'], 'shop_goods.shop_on_sale'=>1,
                    'shop_goods.store_count'=>array('egt', $cg_val['goods_num']), 'shop.is_open'=>1))
                ->select();
            if($shop_goods_list){
                foreach($shop_goods_list as $sg_val){
                    $sg_val['shop_goods_type'] = $goods['shop_goods_type'];
                    $shop_goods_array_shop[$goods['shop_goods_type']][$sg_val['shop_id']][$sg_val['goods_id']] = $sg_val;
                }
                //$shop_goods_array_goods[$cg_val['goods_id']] = $shop_goods_list;
            }else{
                $this->returnInfo(0, '配送渠道库存不足');
            }
        }

        $real_shop_list = array();
        foreach($goods_list as $key => $val){
            foreach($shop_goods_array_shop[$key] as $key2 => $value2){
                if(count($val) == count($value2)){
                    $real_shop_list[$key][] = $key2;
                }
            }
        }

        $shop_goods_array_full = array();
        $shop_ids = array();
        foreach($shop_goods_array_shop as $key => $sgs_val){
            if(count($sgs_val) == $cart_count){
                $shop_goods_array_full[$key] = $sgs_val;
                $shop_ids[] = $key;
            }
        }
        $fields = array('id as shop_id', 'shop_name', 'shop_head_img', 'latitude', 'longitude', 'is_auto_confirm');
        $order = 'id desc';
        if($latitude != -1 && $longitude != -1 ){
            $fields[] = '(2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*('.$latitude.'-latitude)/360),2)+COS(3.1415926535898*'.$latitude.'/180)* COS(latitude * 3.1415926535898/180)*POW(SIN(3.1415926535898*('.$longitude.'-longitude)/360),2))))*1000 as juli';
            $order .= ' , juli asc';
        }else{
            $fields[] = '0 as juli';
        }
        $shopModel = M('shop');
        $shop_where['is_open'] = 1;
        $shop_where['id'] = array('in', $shop_ids);

        foreach($real_shop_list as $key => $val){

            $shop_where['id'] = array('in', $val);

            $shop_info = $shopModel->field($fields)
                ->where($shop_where)
                ->order($order)
                ->find();
            if($shop_info){
                $shop_list_last[$key] = $shop_info;
            }else{
                $this->returnInfo(0, '暂无配送渠道');
                break;
            }
        }

        /*$shop_info = $shopModel->field($fields)
            ->where($shop_where)
            ->order($order)
            ->find();*/

        /*if($shop_info){
            $shop_goods_list_real = $shop_goods_array_full[$shop_info['shop_id']];
        }else{
            $this->returnInfo(0, '暂无配送渠道');
        }*/

        $shop_goods_list_real = array();
        foreach($shop_list_last as $key => $val){
            $shop_goods_list_real[$key] = $shop_goods_array_shop[$key][$val['shop_id']];
        }
        $dada_distance = tpCache('shopping.dd_distance') ? tpCache('shopping.dd_distance') : 7;
        $dada_distance = bcmul($dada_distance, 1000, 2);
        //print_r($shop_goods_list_real);die;
        foreach($goods_list as $key => $t_val){
            foreach($t_val as $g_val) {
                $promPrice = calcGoodsPrice($g_val);
                if ($promPrice['is_prom']) {
                    $prom_type = $g_val['prom_type'];    // 0 普通订单, 3 促销优惠
                    $prom_id = $g_val['prom_id'];      // 活动id
                } else {
                    $prom_type = 0;    // 0 普通订单, 3 促销优惠
                    $prom_id = 0;      // 活动id
                }
                $price = $promPrice['price'];

                $goods_info = $shop_goods_list_real[$key][$g_val['goods_id']];
                $goods_info['goods_price'] = $g_val['shop_price'];
                $goods_info['original_img'] = parseMediaUrl($g_val['original_img']);
                $goods_info['exchange_integral'] = $g_val['exchange_integral'];
                $goods_info['member_goods_price'] = $price;
                $goods_info['prom_type'] = $g_val['prom_type'];
                $goods_info['prom_id'] = $g_val['prom_id'];
                $goods_info['prom_price'] = $price;
                $goods_info['goods_sn'] = $g_val['goods_sn'];
                $goods_info['goods_name'] = $g_val['goods_name'];
                $goods_info['market_price'] = $g_val['market_price'];
                $goods_info['is_free_shipping'] = $g_val['is_free_shipping'];
                $goods_info['weight'] = $g_val['weight'];
                $goods_info['goods_num'] = $g_val['goods_num'];

                if($goods_info['is_city'] == 1 && $shop_list_last[$key]['juli'] > $dada_distance){
                    $this->returnInfo(0, "商品".$goods_info['goods_name']."超出配送范围",
                        array('shop_dist'=>$dada_distance,
                            'real_dist'=>$shop_list_last[$key]['juli'],
                            'goods_id'=>$goods_info['goods_id']
                        ));
                    break;
                }
                $return_goods_array[$shop_list_last[$key]['shop_id']][] = $goods_info;

            }
        }

        $shop_list_last_new = array();
        foreach($shop_list_last as $key => $val){
            $val['shop_goods_type'] = $key;
            $shop_list_last_new[$val['shop_id']] = $val;
        }

        $return_data = array();
        $total_price_sum = 0;
        $post_fee_sum = 0;
        $cut_fee_sum = 0;
        $market_cut_fee_sum = 0;
        $all_exchange_integral = 0;
        $num_sum = 0;
        //print_r($return_goods_array);die;
        foreach($return_goods_array as $key => $rg_val){
            $return_data_val = array();
            $return_data_val['shop_id'] = $shop_list_last_new[$key]['shop_id'];
            $return_data_val['shop_name'] = $shop_list_last_new[$key]['shop_name'];
            $return_data_val['shop_head_img'] = $shop_list_last_new[$key]['shop_head_img'];
            $return_data_val['shop_goods_type'] = $shop_list_last_new[$key]['shop_goods_type'];
            $return_data_val['shop_info'] = $shop_list_last_new[$key];
            $return_data_val['selected'] = 1;

            $total_price = 0;
            $weight = 0;
            $cut_fee = 0;
            $anum = 0;
            $market_cut_fee = 0;
            foreach($rg_val as &$rgv_val){
                $all_exchange_integral += $rgv_val['exchange_integral'] * $rgv_val['goods_num'];
                $rgv_val['goods_fee'] = bcmul($rgv_val['member_goods_price'], $rgv_val['goods_num'], 2);
                $total_price += $rgv_val['goods_fee'];
                $cut_fee += bcmul(bcsub($goods['shop_price'], $rgv_val['member_goods_price'],2), $rgv_val['goods_num'], 2);
                if(!$rgv_val['is_free_shipping']){
                    $weight += bcmul($rgv_val['weight'], $rgv_val['goods_num'], 0);
                }
                $anum += $rgv_val['goods_num'];
                $market_cut_fee += bcmul(bcsub($goods['market_price'], $rgv_val['member_goods_price'],2), $rgv_val['goods_num'], 2);
            }

            $return_data_val['cartList'] = $rg_val;

            if($return_data_val['shop_goods_type'] == 1){
                $post_fee = 0;
            }else{
                $post_fee = \Common\Logic\FeeLogic::getPostFeeNew($rgv_val['shop_id'],$weight, $total_price,$shop_info['juli']);
            }

            $return_data_val['total_price']['total_fee'] = $total_price;
            $return_data_val['total_price']['post_fee'] = $post_fee;
            $return_data_val['total_price']['cut_fee'] = $cut_fee;
            $return_data_val['total_price']['num'] = $anum;
            $return_data_val['total_price']['market_cut_fee'] = $market_cut_fee;

            $return_data['cartList'][] = $return_data_val;

            $total_price_sum += $total_price;
            $post_fee_sum += $post_fee;
            $cut_fee_sum += $cut_fee;
            $market_cut_fee_sum += $market_cut_fee;
            $num_sum += $anum;
        }

        $totalPriceArray = array(
            "total_fee" => $total_price_sum,
            "post_fee" => $post_fee_sum,
            "cut_fee" => $cut_fee_sum,
            "num" => $num_sum,
            "market_cut_fee" =>  $market_cut_fee_sum
        );


        $point_ex_rate = tpCache('shopping.point_rate');//积分兑换比例
        $order_amount_point = intval($total_price * $point_ex_rate);
        $all_exchange_integral = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分

        $return_data['totalPrice'] = $totalPriceArray;
        $userInfo = get_user_info($this->user_id);
        $return_data['available_points'] = isset($userInfo['pay_points']) ? $userInfo['pay_points'] : 0;
        $return_data['all_pay_point'] = $all_exchange_integral;
        $return_data['integral_money'] = $all_exchange_integral / $point_ex_rate;


        $total_amount = bcadd($total_price_sum, $post_fee_sum, 2);;
        if ( bccomp($total_amount,0,2) < 1  )
        {
            $total_amount = 0;
        }
        $order_amount_point = intval( $total_amount * $point_ex_rate );
        $all_pay_point = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分

        if( $pay_points === true )
        {
            $pay_points = $all_pay_point;
        }

        if ($pay_points > 0) {
            if ($pay_points > $all_exchange_integral) {
                $pay_points = $all_exchange_integral;
            }
        } else {
            $pay_points = 0;
        }

        if ($pay_points > 0 && $userInfo && $pay_points > $userInfo['pay_points']) {
            return array('status' => -5, 'msg' => "积分余额不足，你的账户可用积分为:" . $userInfo['pay_points'], 'result' => ''); // 返回结果状态
        }

        $pay_points = ($pay_points / $point_ex_rate ); // 积分支付 100 积分等于 1块钱
        $pay_points = ($pay_points > $total_amount) ? $total_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
        $order_amount = bcsub( $total_amount, $pay_points,2 ); //  积分抵消应付金额


        $orderGoodsModel = M('order_goods');

        $sub_order_data = array();
        $sub_order_data['user_id'] = $this->user_id;
        $sub_order_data['add_time'] = time();
        $sub_order_data['parent_sn'] = $main_order_sn;
        $sub_order_data['consignee'] = $userAddressInfo['consignee'];
        $sub_order_data['mobile'] = $userAddressInfo['mobile'];
        $sub_order_data['zipcode'] = $userAddressInfo['zipcode'];
        $sub_order_data['province'] = $userAddressInfo['province'];
        $sub_order_data['city'] = $userAddressInfo['city'];
        $sub_order_data['district'] = $userAddressInfo['district'];
        //$sub_order_data['twom'] = $usertwomInfo['twom'];
        $sub_order_data['province_name'] = $userAddressInfo['province_name'];
        $sub_order_data['city_name'] = $userAddressInfo['city_name'];
        $sub_order_data['district_name'] = $userAddressInfo['district_name'];
        //$sub_order_data['twom_name'] = $usertwomInfo['twom_name'];
        $sub_order_data['address'] = $userAddressInfo['address'];
        $sub_order_data['receiver_lng'] = $userAddressInfo['longitude'];
        $sub_order_data['receiver_lat'] = $userAddressInfo['latitude'];
//print_r($return_data);die;
        foreach ($return_data['cartList'] as $k => &$v) {
            $sub_order_data['goods_price'] = $v['total_price']['total_fee'];
            $sub_order_data['user_note'] = ($remark_array && $remark_array[$v['shop_id']] && $remark_array[$v['shop_id']] != 'null')
                ? ($remark_array[$v['shop_id']]) : ($remark_array && $remark_array[$k] ? $remark_array[$k] : '');
            $sub_order_data['order_sn'] = 'S' . $this->_createOrderSN();
            $sub_order_data['shipping_price'] = $v['total_price']['post_fee'];  // 快递费
            $sub_order_data['shop_id'] = $v['shop_id'];
            //$sub_order_data['order_status'] = $return_data['cartList'][0]['shop_info']['is_auto_confirm'];


            $sub_order_data['total_amount'] = bcadd($v['total_price']['total_fee'], $v['total_price']['post_fee'],2);
            $sub_order_data['order_amount'] = bcadd($v['total_price']['total_fee'], $v['total_price']['post_fee'],2);
            $sub_order_data['total_buy_number'] = $v['total_price']['num'];
            $sub_order_data['order_type'] = $v['shop_goods_type'] == 0 ? 1 : 2;
            $subOrderId = M('order')->data($sub_order_data)->add();


            if ($subOrderId <= 0) {
                M()->rollback(); // 事务回滚
                $this->returnInfo(0, '子订单表写入失败, 未知原因');
            }
            add_shop_message($sub_order_data['shop_id'], '新的订单', '您有新的订单，请前往查看处理',1, $subOrderId);
            //写入订单日志
            $logResult = order_log($sub_order_data['order_sn'], '', '提交订单', 1);
            if ($logResult === false) {
                M()->rollback(); // 事务回滚
                $this->returnInfo(0, '订单日志写入失败, 未知原因');
            }

            #写入订单商品表
            $order_goods_data = [];
            $order_goods_data['order_id'] = $subOrderId;
            $order_goods_data['order_sn'] = $sub_order_data['order_sn'];

            $order_goods_data['user_id'] = $this->user_id;
            foreach ($v['cartList'] as $ke => $val) {

                $order_goods_data['goods_id'] = $val['goods_id'];
                $order_goods_data['goods_name'] = $val['goods_name'];
                $order_goods_data['goods_price'] = $val['goods_price'];
                $order_goods_data['member_goods_price'] = $val['member_goods_price'] > 0 ? $val['member_goods_price'] : $order_goods_data['goods_price'];
                $order_goods_data['goods_num'] = $val['goods_num'];

                $goodsOrderId = $orderGoodsModel->data($order_goods_data)->add();
                if ($goodsOrderId <= 0) {
                    M()->rollback(); // 事务回滚
                    $this->returnInfo(0, '订单商品表写入失败, 未知原因');
                }
                $order_sns = $sub_order_data['order_sn'];
                session_start();
                $_SESSION["order_sn"] = $order_sns;
                // 下面减少库存
                $sonStorge = $this->decreaseShopGoodsNumber($order_sns);
                if ($sonStorge === false) {
                    M()->rollback(); // 事务回滚
                    $this->returnInfo(0, '库存处理失败, 未知原因');
                }
                //写入订单日志
                order_log($order_sns, '', '减少库存成功', 1);
            }
        }

        $main_order_data = array(); // 写要入order表中的 主定单 数据
        $main_order_data['user_id'] = $this->user_id;
        $main_order_data['add_time'] = time();
        $main_order_data['order_sn'] = $main_order_sn;
        $main_order_data['integral_money'] = $all_pay_point / $point_ex_rate;
        $main_order_data['total_buy_number'] = $num_sum;
        $main_order_data['total_amount'] = $total_amount;
        $main_order_data['order_amount'] = $order_amount;
        $main_order_data['shipping_price'] = $post_fee_sum;
        $main_order_data['integral'] = $all_pay_point;
        $main_order_data['goods_price'] = $total_price_sum;
        $main_order_data['real_pay_amount'] = $order_amount; // 实际支付的金额
        $mainOrderId = M('order')->data($main_order_data)->add();
        // var_dump($main_order_data,$pay_points);
        if ($mainOrderId <= 0) {
            M()->rollback(); // 事务回滚
            $this->returnInfo(0, '主订单表写入失败, 未知原因');
        }

        #如果使用积分，先扣
        if ($pay_points) {

            if( $pay_points === true )
            {
                $pay_points = $all_pay_point;
            }

            if ($all_pay_point > $pay_points) {
                $this->returnInfo(-1, '无足够积分支付抵扣');
            }

            if (!$userInfo || $userInfo['pay_points'] < $pay_points) {
                $this->returnInfo(-1, '积分余额不足');
            }

            $log = accountLog($this->user_id, 0, $all_pay_point, '下单抵扣' . $main_order_sn, 0, $mainOrderId, $main_order_sn);

            if (!$log || !$log['is_success']) {
                M()->rollback();
                $this->returnInfo(-1, isset($res['message']) ? $res['message'] : '积分抵扣失败!');
            }
        }

        // 清除购物车
        unset($where);
        $where['selected'] = 1;
        $where['status'] = 1; // 商品有效
        if ($this->del($where)) {
            M()->commit(); // 事务提交
            unset($where);
            return $main_order_sn;
        } else {
            M()->rollback(); // 事务回滚
            $this->returnInfo(0, '清除购物车失败, 未知原因');
        }
    }


    /**
     * 减少库存
     * @param $order_sn 要减库存的定单SN
     */
    public function decreaseGoodsNumber($order_sn)
    {
        $where['order_sn'] = $order_sn;
        $orderGoodsData = M('OrderGoods')->field('goods_id,goods_name, goods_name,spec_key, goods_num')->where($where)->select();
        foreach ($orderGoodsData as $value) {
            try {
                $this->change_goods_storage($value['goods_id'], $value['spec_key'], 0 - $value['goods_num']);
            } catch (\Exception $e) {
                // var_dump($e);
                if ($e->getCode() == 22003) {
                    $this->returnInfo(-1, "商品:{$value['goods_name']}库存不足");
                }
                throw $e;
            }
        }
    }


    /**
     * 改变商品规格库存
     * @param int $goods_id 商品id
     * @param string $key 商品规格key值
     * @param int $buy_number 数量 
     */
    public function change_goods_storage($goods_id, $key, $buy_number)
    {
        $where['goods_id'] = $goods_id;
        $where['key'] = $key;
        $res = M('spec_goods_price')->where($where)->setInc('store_count', $buy_number);
        $res = M('goods')->where("goods_id=$goods_id")->fetchSql(0)->setInc('store_count', $buy_number);
            // var_dump($res);
            //检测商品是否参加秒杀活动
        $kill = M('flash_sale')->where("goods_id=$goods_id and is_end=0")->find();
            //检测商品是否参加团购
            // $group = M('group_buy')->where("goods_id=$goods_id and recommended=1")->find();
            //检测商品是否参加品牌清仓
        $qin = M('prom_goods as pg')->join('ln_goods as gs on gs.prom_id=pg.id')->where("gs.goods_id=$goods_id")->find();
        $where['goods_id'] = $goods_id;
        if (!empty($kill)) {
            $res = M('flash_sale')->where($where)->setInc('goods_num', $buy_number);
        }
            // if (!empty($group)) {
            //     $res = M('group_buy')->where($where)->setInc('goods_num', $buy_number);
            // }
        if (!empty($qin)) {
            $res = M('prom_goods as pg')->join('ln_goods as g on g.prom_id=pg.id')->where("g.goods_id=$goods_id")->setInc('goods_num', $buy_number);
        }
        return $res;
    }


    /**
     * 删除购物车商品
     * @param $where 删除条件
     * @return bool
     */
    public function del($where)
    {
        if (M('cart')->where('user_id=' . $this->user_id)->where($where)->delete() !== false) {
            return true;
        }
        return false;
    }


    public function getSpecItem($item_id)
    {
        $where['id'] = $item_id;
        return M('spec_item')->where($where)->getField('item');
    }



    // 进入定单之前, 判断购物车是否正常
    public function checkCart()
    {
        $where['user_id'] = $this->user_id;
        $where['selected'] = 1;
        $cartGoodsIds = M('cart')->distinct(true)->field('goods_id')->where($where)->select();
        foreach ($cartGoodsIds as $key => $value) {
            $goods_id = $cartGoodsIds[$key]['goods_id'];
            $map['goods_id'] = $goods_id;
            $cartGoods = M('cart')->where($where)->where($map)->select();
            $goods_spec_key_array = array();
            $buy_number_array = array();
            foreach ($cartGoods as $k => $v) {
                if ($cartGoods[$k]['status'] == 0)
                    return V(0, '进货车中有无效商品, 请先清除无效商品');
                $goods_spec_key_array[] = $cartGoods[$k]['spec_key_name'];
                $buy_number_array[] = $cartGoods[$k]['goods_num'];
            }

            // 判断商品是否可以购买
            $result = $this->checkGoodsCanBuy($goods_id, $goods_spec_key_array, $buy_number_array);
            if ($result['is_on_sale'] !== 1) {
                return $result;
            }
        }

        return V(1, '购物车审核通过!');
    }

    public function getUserAddressInfo($address_id)
    {
        $where['address_id'] = $address_id;
        $where['user_id'] = $this->user_id;
        $info = M('user_address')->field('address_id', 'consignee', 'address', 'province', 'city', 'district', 'mobile', 'zipcode', 'is_default')->where($where)->find();
        return $info;
    }

    /**
     * 查看商品能不能进行购买, 如果能返回商品的基础信息, 如果不能返回错误信息
     * @param int $goods_id 商品ID
     * @param int $buy_number 用户购买数量
     * @return array
     */
    public function checkGoodsCanBuy($goods_id, $goods_spec_key_array, $buy_number_array)
    {
        if ($goods_id <= 0 || count($buy_number_array) <= 0 || count($goods_spec_key_array) <= 0) {
            return V(0, '参数不正确!');
        }

        $return_goods_info = array();
        $where['goods_id'] = $goods_id;
        $goods_info = $this->getGoodsInfo($where, 'goods_name,is_on_sale,shop_price, shop_id');
        if ($goods_info) {
            $buy_number_total = array_sum($buy_number_array);

            // $buyUserId = $this->getShopUserId($goods_info['shop_id']);
            // if ($buyUserId == $this->user_id) {
            //    return (0, '不能购买自己店铺商品');
            // }

            if ($goods_info['is_on_sale'] == 0) {
                $return_goods_info['goods_id'] = $goods_id;
                $return_goods_info['goods_name'] = $goods_info['goods_name'];
                return V(0, '商品已下架', $return_goods_info);
            }

            if ($buy_number_total < $goods_info['store_count']) {
                return V(0, '购买数量不能小于库存数量');
            }
            foreach ($goods_spec_key_array as $key => $value) {
                if ($value) {
                    $storage = $this->get_storage($goods_id, $value);
                    if ($storage < $buy_number_array[$key]) {
                        $return_goods_info['goods_id'] = $goods_id;
                        $return_goods_info['goods_name'] = $goods_info['goods_name'];
                        $return_goods_info['spec_key'] = $value;
                        return V(0, '商品库存数量不足', $return_goods_info);
                    }
                } else {
                    $buy_price = $goods_info['shop_price'];
                    $return_goods_info['buy_price'] = $buy_price;
                    return V(1, '商品信息', $goods_info);
                }

            }
            $buy_price = $goods_info['shop_price'];
            $return_goods_info['buy_price'] = $buy_price;
            return V(1, '商品信息', $goods_info);
        } else {
            return V(0, '商品已经不存在了!');
        }
    }



    /**
     * 获取商品规格库存
     * @param $goods_id int 商品id
     * @return array
     */
    public function get_storage($goods_id, $spec_key)
    {
        $where['goods_id'] = $goods_id;
        $where['key_name'] = $spec_key;
        $result = M('spec_goods_price')->where($where)->getField('store_count');
        return $result;
    }


    /**
     * 根据店铺ID, 获取用户ID
     * @param $shop_id
     * @return mixed
     */
    public function getShopUserId($shop_id)
    {
        $where['shop_id'] = $shop_id;
        return M('shop')->where($where)->getField('user_id');
    }


    /**
     * 获取商品的详情
     */
    public function getGoodsInfo($where, $field = null)
    {
        if ($field == null) $field = array(
            'goods_id', 'goods_name', 'shop_id', 'shop_name', 'shop_price', 'store_count', 'sales_sum', 'comment_num', 'collect_num',
            'original_img', 'click_count', 'cat_id', 'on_time', 'is_on_sale'
        );
        $map['is_on_sale'] = 1;

        $info = M('goods')->field($field)->where($where)->where($map)->find();

        if (!empty($info)) {
            $token = I('post.token'); //接口调用
            if ($token) {
                $uid = $this->getUID($token);
            } else {
                $uid = $this->user_id;
            }
            //商品是否收藏
            if ($uid) {
                $is_favorite = $this->isUserFavorite($where['goods_id'], $uid);
            }
            $info['is_favorite'] = $is_favorite ? $is_favorite : 0;
        }
        return $info;
    }


    /**
     * 商品是否收藏
     * @param $user_id
     * @param $goods_id
     * @return int
     */
    public function isUserFavorite($goods_id, $uid = UID)
    {
        $where['user_id'] = $uid;
        $where['goods_id'] = $goods_id;
        $userFavoriteInfo = M('goods_collect')->where($where)->find();
        if (is_null($userFavoriteInfo)) {
            return 0;
        }
        return 1;
    }


    //根据token获取uid
    public function getUID($token)
    {
        $where['token'] = $token;
        $userId = M('users')->where($where)->getField('user_id');
        return $userId;
    }


    //立即购买、团购、兑换
    public function cart4()
    {
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        if ($this->user_id == 0) {
            $this->returnInfo('-1', '请先登录');
        }

        $goods_num = I("goods_num");// 商品数量
        //$goods_spec = I("goods_spec"); // 商品规格
        //$goods_spec = explode(',', $goods_spec);
        //$goods_spec = implode('_', $goods_spec);

        if ($goods_num <= 0) {
            $this->returnInfo(-1, "请选择购买数量", '');
        }

        #团购准备下单
        $group_buy_id = I("groupbuy_id", 0);
        if ($group_buy_id) {
            try {
                $res = \Common\Logic\GroupbuyLogic::preCreateOrder([
                    "user_id" => $this->user_id,
                    "groupbuy_id" => $group_buy_id,
                    //"spec_key" => $goods_spec,
                    "num" => $goods_num
                ]);
            } catch (\Exception $e) {
                $this->returnInfo($e->getCode(), $e->getMessage(), "");
            }

            $this->returnInfo(1, "获取成功", $res);
        }

        $goods_id = I('goods_id', 0);

        #兑换准备下单
        $exchange_buy = I("exchange_buy", 0);
        if ($exchange_buy) {
            try {
                $res = \Common\Logic\ExchangebuyLogic::preCreateOrder([
                    "user_id" => $this->user_id,
                    "goods_id" => $goods_id,
                    //"spec_key" => $goods_spec,
                    "num" => $goods_num
                ]);
            } catch (\Exception $e) {
                $this->returnInfo($e->getCode(), $e->getMessage(), "");
            }

            $this->returnInfo(1, "获取成功", $res);
        }

        $usersInfo = M('users')->where([
            "user_id" => $this->user_id
        ])->field("user_id,pay_points,user_money")->find();
        
        // $goods_spec = json_decode($goods_spec, true); //app 端 json 形式传输过来
        $now = time();        
        $addresslist = M('UserAddress')
        ->where(["user_id"=>$this->user_id])
        ->order("is_default desc")
        ->limit(1)
        ->select();
        // 优惠券
        $Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的     
        $sql = "select c1.name,c1.money,c1.condition, c2.* from ln_coupon as c1 inner join ln_coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,5) and order_id = 0  where c2.uid = {$this->user_id}  and " . time() . " < c1.use_end_time and c1.use_start_time < " . time();
        $couponList = $Model->query($sql);
        // $c = M('UserAddress')->where("user_id = {$this->user_id} and is_default = 1")->count(); // 看看有没默认收货地址        	
		//商品信息
        $goods = M('goods')->where(array('goods_id'=>$goods_id, 'is_on_sale'=>1))->find();
        if ($goods) {
            $latitude = -1;
            $longitude = -1;
            if($addresslist){
                $latitude = $addresslist[0]['latitude'];
                $longitude = $addresslist[0]['longitude'];
            }
            $shop_goods = M('shop_goods')->alias('shop_goods')
                ->field('shop_goods.*')
                ->join('ln_shop as shop on shop_goods.shop_id = shop.id', 'left')
                ->where(array('shop_goods.goods_id'=>$goods_id, 'shop_goods.shop_on_sale'=>1, 'shop_goods.store_count'=>array('egt', $goods_num), 'shop.is_open'=>1))
                ->select();

            if($shop_goods){
                $shop_ids = array();
                //$goods_store = 0;
                $shop_goods_array = array();
                foreach($shop_goods as $val){
                    $shop_ids[] = $val['shop_id'];
                    //$goods_store += $val['store_count'];
                    $shop_goods_array[$val['shop_id']] = $val;
                }
                /*if($goods_store < $goods_num){
                    $this->returnInfo(0, "库存不足", '');
                }*/
                $shop_ids = get_arr_column($shop_goods, 'shop_id');
                $fields = array('id as shop_id', 'shop_name', 'shop_head_img', 'latitude', 'longitude');
                $order = 'id desc';

                if($latitude != -1 && $longitude != -1 ){
                    $fields[] = '(2 * 6378.137* ASIN(SQRT(POW(SIN(3.1415926535898*('.$latitude.'-latitude)/360),2)+COS(3.1415926535898*'.$latitude.'/180)* COS(latitude * 3.1415926535898/180)*POW(SIN(3.1415926535898*('.$longitude.'-longitude)/360),2))))*1000 as juli';
                    $order .= ' , juli asc';
                }else{
                    $fields[] = '0 as juli';
                }
                $shop_where['is_open'] = 1;
                $shop_where['id'] = array('in', $shop_ids);
                $shop_info = M('shop')->field($fields)
                    ->where($shop_where)
                    ->order($order)
                    ->find();
                if($goods['is_city'] == 1){
                    $dada_distance = tpCache('shopping.dd_distance');
                    $dada_distance = bcmul($dada_distance, 1000, 2);
                    if($shop_info['juli'] > $dada_distance){
                        $this->returnInfo(0, "商品超出配送范围", array('shop_dist'=>$dada_distance, 'real_dist'=>$shop_info['juli'] ));
                    }
                }

                //$flag_goods_num = $goods_num;
                $return_data = array();

                $all_exchange_integral = 0;
                $promPrice = calcGoodsPrice( $goods);
                $price = $promPrice['price'];

                $prom_price = $price;  // 活动价
                $member_goods_price = $price;

                $total_price_sum = 0;
                $post_fee_sum = 0;
                $cut_fee_sum = 0;
                $market_cut_fee_sum = 0;

                if( $promPrice['is_prom'] )
                {
                    $prom_type = $goods['prom_type'];    // 0 普通订单, 3 促销优惠
                    $prom_id = $goods['prom_id'];      // 活动id
                }else{
                    $prom_type = 0;    // 0 普通订单, 3 促销优惠
                    $prom_id = 0;      // 活动id
                }

                //foreach($shop_list as $val){
                    //$shop_info = $val;
                    $shop_info['shop_head_img'] = parseMediaUrl($val['shop_head_img']);
                    $goods_info = $shop_goods_array[$shop_info['shop_id']];

                    //if($flag_goods_num <= $shop_goods_array[$val['shop_id']]['store_count']){
                        $goods_info['goods_num'] = $goods_num;
                        $return_data[] = array(
                            'shop_id' => $shop_info['shop_id'],
                            'shop_name' => $shop_info['shop_name'],
                            'shop_head_img' => $shop_info['shop_head_img'],
                            'shop_info'=>$shop_info,
                            'selected'=>1,
                            'cartList'=>array($goods_info),
                        );
                        //break;
                    //}else{
                        /*$goods_info['goods_num'] = $shop_goods_array[$val['shop_id']]['store_count'];
                        $return_data[] = array(
                            'shop_id' => $val['shop_id'],
                            'shop_name' => $val['shop_name'],
                            'shop_head_img' => parseMediaUrl($val['shop_head_img']),
                            'shop_info'=>$shop_info,
                            'selected'=>1,
                            'cartList'=>array($goods_info),
                        );
                        $flag_goods_num -= $shop_goods_array[$val['shop_id']]['store_count'];*/
                    //}
                //}

                foreach($return_data as &$val){
                    $total_price = 0;
                    $weight = 0;
                    $cut_fee = 0;
                    $anum = 0;
                    $market_cut_fee = 0;
                    foreach($val['cartList'] as &$val2){
                        $val2['goods_price'] =  $goods['shop_price'];
                        $val2['original_img'] = parseMediaUrl($goods['original_img']);
                        $all_exchange_integral += $goods['exchange_integral'] * $val2['goods_num'];
                        $val2['member_goods_price'] = $price;
                        $val2['prom_type'] = $prom_type;
                        $val2['prom_id'] = $prom_id;
                        $val2['prom_price'] = $prom_price;
                        $val2['goods_sn'] = $goods['goods_sn'];
                        $val2['goods_name'] = $goods['goods_name'];
                        $val2['market_price'] = $goods['market_price'];
                        $val2['goods_fee'] = (($val2['goods_num'] * $member_goods_price) * 100) / 100;
                        $total_price += $val2['goods_fee'];
                        $cut_fee += ((($goods['shop_price'] - $member_goods_price) * $val2['goods_num']) *100)/100;
                        if( !$goods['is_free_shipping'] )
                        {
                            $weight += $goods['weight'] * $val2['goods_num'] ;
                        }
                        $anum += $val2['goods_num'];
                        $market_cut_fee += ((($goods['market_price'] - $member_goods_price) * $val2['goods_num']) *100)/100;
                    }

                    if($goods['shop_goods_type'] == 0){
                        $post_fee = \Common\Logic\FeeLogic::getPostFeeNew($val['shop_id'], $weight, $total_price, $val['shop_info']['juli']);
                    }else{
                        $post_fee = 0;
                    }

                    $val['total_price'] = array(
                        'total_fee' => $total_price,
                        'post_fee' => $post_fee,
                        'cut_fee' => $cut_fee,
                        'num' => $anum,
                        'market_cut_fee' => $market_cut_fee
                    );
                    $total_price_sum += $total_price;
                    $post_fee_sum += $post_fee;
                    $cut_fee_sum += $cut_fee;
                    $market_cut_fee_sum += $market_cut_fee;
                }

                $point_rate = tpCache('shopping.point_rate');

                $total_price_arr = array(
                    'total_fee' => $total_price_sum,
                    'post_fee' => $post_fee_sum,
                    'cut_fee' => $cut_fee_sum,
                    'num' => $goods_num,
                    'market_cut_fee' => $market_cut_fee_sum
                ); // 总计
                $total_price_arr['total_fee'] = $total_price_arr['total_fee'] + $total_price_arr['post_fee'];


                $result['cartList'] = $return_data;
                $result['totalPrice'] = $total_price_arr;
                $result['addressList'] = $this->getAddressInfo($addresslist);
                $result['couponList'] = $couponList;
                $result['available_points'] = $usersInfo ? $usersInfo['pay_points'] : 0;
                $order_amount_point = intval($total_price_sum * $point_rate);
                $all_pay_point = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分
                $result['all_pay_point'] = $all_pay_point ; //需用的积分
                $result['integral_money'] = $all_pay_point / $point_rate;//积分抵扣金额
                $this->returnInfo(1, "获取成功", $result);
            }else{
                $this->returnInfo(0, "暂无配送渠道", '');
            }
        } else {
            $this->returnInfo(0, "商品已下架", '');
        }
    }


    /**
     * 将商品批量加入购物车
     */
    public function batchAddCart()
    {
        $goods_id = I("goods_id", 0, 'intval'); // 商品id
        //$shop_info = M('goods')->field('shop_id')->where("goods_id=$goods_id")->select();
        //$shop_id = $shop_info[0]['shop_id'];
        if ($goods_id == 0) {
            $result = array('status' => -1, 'msg' => '商品信息有误！', 'result' => '');
        } else {
            $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
            $goods_spec = I('goods_spec');      //规格数组
            $goods_count = I('goods_num');    //数量数组
			// p($goods_count);die;
            // foreach($goods_spec as $k => $value){
            $goods_spec = explode(',', $goods_spec);
            $goods_spec = implode('_', $goods_spec);
            $goods_num = $goods_count;
            if ($this->user_id == 0) {
                $this->returnInfo('-1', '请先登录');
            }
            $result = $this->cartLogic->addCart($goods_id, $goods_num, $goods_spec, $unique_id, $this->user_id); // 将商品加入购物车
                // if($result['status'] < 0){
                //     exit();
                // }
            // }
        }
        exit(json_encode($result));
    }

    public function cart5()
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            $this->returnInfo('-1', '缺少参数', '');
        }
        $order_id = I('order_id');
        if (!$order_id) {
            $this->returnInfo('-1', '订单不存在');
        }
        $where['user_id'] = $user_id;
        $where['order_id'] = $order_id;
        $orderInfo = M('order')->field('order_sn,add_time,shipping_price ,order_amount as total_amount,goods_price, coupon_price, integral as pay_points')->where($where)->find();
        $add_time = $orderInfo['add_time'];
        $orderInfo['deadline_time'] = $add_time + 1800;
        $point_rate = tpCache('shopping.point_rate');
        ##增加信息
        $orderInfo['payables'] = $orderInfo['total_amount'];
        $userInfo = M("users")->where([
            "user_id" => $this->user_id
        ])->field("user_id,user_money")->find();
        $orderInfo['available_user_money'] = $userInfo['user_money'];

        $this->returnInfo('1', '获取成功', [
            'deadline_time' => $orderInfo['deadline_time'],#支付截止时间
            'add_time' => $orderInfo['add_time'],#订单创建时间
            'postFee' => $orderInfo['shipping_price'],#邮费
            'couponFee' => $orderInfo['coupon_price'],#优惠券抵消金额
            'payables' => $orderInfo['payables'],#应付费用
            'goodsFee' => $orderInfo['payables'] - $orderInfo['shipping_price'],#商品总价
            'pointsFee' => $orderInfo['pay_points'] / $point_rate,#积分抵消费用
            'pay_points' => $orderInfo['pay_points'],#积分抵消部分所扣积分
            'available_user_money' => $orderInfo['available_user_money'],#账户可用余额
            "order_sn" => $orderInfo['order_sn'] #订单号
        ]);
    }

    public function decreaseShopGoodsNumber($order_sn){
        $where['order_goods.order_sn'] = $order_sn;
        $orderGoodsData = M('OrderGoods')->alias('order_goods')
            ->join('ln_order as ord on order_goods.order_sn = ord.order_sn')
            ->field('order_goods.goods_id, order_goods.goods_num, ord.shop_id')
            ->where($where)
            ->select();
        foreach ($orderGoodsData as $value) {
            $this->change_goods_storage_new($value['goods_id'], $value['shop_id'], 0 - $value['goods_num']);
        }
    }

    /**
     * 修改渠道，和系统库存数据，修改系统销售数据
     * @param $goods_id
     * @param $shop_id
     * @param $number
     * @return bool
     */
    public function change_goods_storage_new($goods_id, $shop_id, $number){
        $where['goods_id'] = $goods_id;
        $where['shop_id'] = $shop_id;
        $warning_storage = tpCache('basic.warning_storage');
        $shop_goods_info = M('shop_goods')->field('id, store_count')->where($where)->getField('store_count');
        if($shop_goods_info['store_count'] - $number <= $warning_storage){
            add_shop_message($shop_id, '补货提醒', '商品库存警告',2, $shop_goods_info['id']);
        }
        $is_success_shop_goods = M('shop_goods')->where($where)->setInc('store_count', $number);
        $is_success_goods_count = M('goods')->where(array('goods_id'=>$goods_id))->setInc('store_count', $number);
        $is_success_goods_sales_num = M('goods')->where(array('goods_id'=>$goods_id))->setDec('sales_sum', $number);

        return $is_success_shop_goods !== false && $is_success_goods_count !==false && $is_success_goods_sales_num !== false;
    }


}
